/*
 * @Author: liuqiang
 * @Date: 2021-02-08 15:22:11
 * @Last Modified by: liuqiang
 * @Last Modified time: 2021-03-02 15:31:17
 */
const { beforeRouter } = require('../utils/routerGuard');
const { readFileName } = require('../utils/tool');

// const routers = ["user", "customer", "bill"];
const routers = readFileName(__dirname);

function initRouter(app) {
  app.use(beforeRouter);

  routers.forEach((item) => {
    const router = require('./' + item);
    app.use(router.routes()).use(router.allowedMethods());
  });

  app.use(async (ctx, next) => {
    // 错误处理
    try {
      await next();
      if (!ctx.body) {
        ctx.status = 404;
        ctx.body = {
          err: -99,
          msg: '访问的接口不存在！',
        };
      }
    } catch (err) {
      ctx.status = 500;
      ctx.body = {
        err: -999,
        msg: '系统错误！',
      };
    }
  });
}

module.exports = {
  initRouter,
};
